//
//  MediaLibraryAccess_04ViewController.m
//  MediaLibraryAccess_04
//
//  Created by 畑圭輔 on 10/02/07.
//  Copyright Keisuke Hata 2010. All rights reserved.
//

#import "MediaLibraryAccess_04ViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@implementation MediaLibraryAccess_04ViewController

@synthesize items = _items;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	// searchbar init
	_searchSongBar.showsCancelButton = YES;
	
	// 曲のタイトルでグルーピングされたデータタイプが"Music"のクエリーを取得します。
	_songQuery = [[MPMediaQuery songsQuery] retain];

	// NSOperationQueueを生成します。
	// 一度に実行できるスレッドを１つに限定します。
	_searchQueue = [[NSOperationQueue alloc] init];
	[_searchQueue setMaxConcurrentOperationCount:1];
	
    [super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[_items release];
	[_songQuery release];
	[_searchQueue cancelAllOperations];
	[_searchQueue release];
    [super dealloc];
}

#pragma mark -
#pragma mark SearchBar Delegate

//　キーボードを閉じる時
- (void) closeKeyboard
{
	[_searchSongBar resignFirstResponder];
}

// キャンセルボタンが押された時
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
	[_searchQueue cancelAllOperations];
	[self closeKeyboard];
}

// 検索ボタンが押された時
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	// 検索開始
	NSLog(@"%@",searchBar.text);
	SongSearchOperation *op = [[SongSearchOperation alloc] initWithSearchItem:searchBar.text searchQuery:_songQuery];
	op.resultsDeleate = self;
	[_searchingIndicatorView startAnimating];
	[_searchQueue addOperation:op];
	[op release];
}

#pragma mark -
#pragma mark SongSearchOperationResultsDelegate

// NSOperationが終了した時に呼ばれるデリゲート
-(void) operationFinishedSearch : (SongSearchOperation *)op {
	
	// キャンセルされている時は即座に抜ける
	if( [op isCancelled] )
		return;
	
	if( [NSThread isMainThread] ) {
		
		_items = [op.items retain];
		[_searchingIndicatorView stopAnimating];
		[_searchResult reloadData];
		
	}else {
		// メインスレッドじゃない時：UIKitの操作は、メインスレッド以外では行ってはいけない
		[self performSelectorOnMainThread:@selector(operationFinishedSearch:) 
				withObject:op waitUntilDone:NO];
	}
}


#pragma mark -
#pragma mark TableView Delegate

// テーブルビューセルの高さ
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  {
	return kSongSearchResultTableViewCellHeight;
}


#pragma mark -
#pragma mark TableView DataSource

// テーブルビューセルの数
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section  {
	return [_items count];
}

// テーブルビューセルを生成し、設定する
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	NSUInteger		row		= indexPath.row;
	static NSString *reuseID = @"songSearchResultID";
	
	// try to recycle!
	UITableViewCell	*cell	= (UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:reuseID];
	
	if( cell == nil ) {
		cell = [[[UITableViewCell alloc] 
				 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID] autorelease];
	} else {
	}
	MPMediaItem *item = [_items objectAtIndex:row];
	cell.textLabel.text = [item valueForProperty:MPMediaItemPropertyTitle];
	return cell;
}


@end
